/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  Image,
  TextInput,
  View,
  Platform,
  NativeModules,
} from 'react-native';

import Toast from 'react-native-root-toast';

import Head from './head.js'
import CockpitModal from './modal.js'
import CockpitGesturePassword from './CockpitGesturePassword.js';
import CockpitResetGesturePassword from './CockpitResetGesturePassword.js';
import ExitAndroid from './exit.js';
import Download from './version.js';

let OldPassword='';
let NewPassword='';
let AgainPassword='';
let _this;

export default class Set extends Component {
    constructor(props) {
        super(props);
        _this = this;
        this.state = {
            passwordAlertHeight: 0,
            passwordAlert: [],
            nowVersion: '1.0.0',
            lastestVersion: '1.0.0',
            downloadURL: '',
            downloadPath: '/cockpit/download/',
            appName: 'cockpit',

        };
    }

    toCockpitIndConfig(){
        
    }

    versionCheck(){
        if (Platform.OS == 'ios'){
            this.refs.iosVersionModal.showModal();
        }else{
            this.versionCheckAndroid();
        }
    }

    versionCheckAndroid(){
        let downloadURL;
        Download.getVersion((version) => {
            let ret = cockpitGet.versionCheck(version);
            ret.then((response) => response.json())
            .then((responseJson) => {
                // console.warn(JSON.stringify(responseJson))
                if (responseJson.retcode == 0 || responseJson.retcode == '0') {
                    let fileRelativePath = responseJson.result.versionInfo.fileRelativePath;
                    let versionNumber = responseJson.result.versionInfo.versionNumber;
                    downloadURL = cockpitGet.getVersionUrl(fileRelativePath);
                    this.setState({
                        nowVersion: version,
                        lastestVersion: versionNumber,
                        downloadURL: downloadURL,
                        appName: 'cockpit' + versionNumber,
                    });
                    // Download.startDownload(downloadURL, "/cockpit/download/", "cockpit"+versionNumber);
                    this.refs.versionModal.showModal();
                }else{
                    Toast.show(responseJson.retmsg == null ? "版本校验失败" : responseJson.retmsg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
                }
            })
            .catch((error) => {
                //Toast.show(error == null ? "系统异常" : JSON.stringify(error), {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
                Toast.show("请检查网络设置", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            });
        })
    }

    versionDownload(){
        Download.startDownload(this.state.downloadURL, this.state.downloadPath, this.state.appName);
    }

    aboutModalShow(){
        this.refs.aboutModal.showModal();
    }
    passwordModalShow(){
        this.refs.passwordModal.showModal();
    }
    passwordModalHidden(){
        this.refs.passwordModal.hiddenModal();
    }
    exitModalShow(){
        this.refs.exitModal.showModal();
    }


    //输入的旧密码
    updateLoginName_Old(text){
        OldPassword=text;
    }    
    

    //输入的新密码
    updateLoginName_New(text){
        NewPassword=text
    }

    //再次输入的新密码
    updateLoginName_again(text){
        AgainPassword=text
    }

    //取消按钮
    _ModifySet(){
        this.setState({
            passwordAlertHeight: 0,
            passwordAlert:[]
        })
    }
    _MP_renderErrorMsg(msg){
        return <View style={styles.passAlert}>
                    <Text style={{color:'red',fontSize:14}}>
                        {msg}
                    </Text>
                </View>
    }

    _ModifyPassword(){
        let reg = new RegExp("[\\u4E00-\\u9FFF]+") 
        if (OldPassword == '') {
            this.setState({
                passwordAlertHeight: 20,
                passwordAlert: this._MP_renderErrorMsg('请输入旧密码')
            })
            
        }else if (AgainPassword == '' || NewPassword == '') {
            this.setState({
                passwordAlertHeight: 20,
                passwordAlert: this._MP_renderErrorMsg('请输入新密码')
            })
            
        }else if (AgainPassword !== NewPassword) {
            this.setState({
                passwordAlertHeight: 20,
                passwordAlert: this._MP_renderErrorMsg('输入密码不一致')
            })
        }else if(NewPassword.length < 6){
            this.setState({
                passwordAlertHeight: 20,
                passwordAlert: this._MP_renderErrorMsg('密码长度至少6位')
            })
        }else if(reg.test(NewPassword)){
            this.setState({
                passwordAlertHeight: 20,
                passwordAlert: this._MP_renderErrorMsg('密码不可含有中文')
            })
        }else{
            let ret = cockpitGet.updateMobilePwd(OldPassword, NewPassword, userid);
            ret.then((response) => response.json())
            .then((responseJson) => {
                if (responseJson.retcode == 0 || responseJson.retcode == '0') {
                    this.setState({
                        passwordAlertHeight: 0,
                        passwordAlert:[]
                    })
                    this.passwordModalHidden();
                    Toast.show("密码修改成功", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
                }else{
                    //Toast.show(responseJson.retmsg == null ? "密码修改失败" : responseJson.retmsg, {duration: Toast.durations.SHORT, position: Toast.positions.BOTTOM});
                    this.setState({
                        passwordAlertHeight: 20,
                        passwordAlert: this._MP_renderErrorMsg(responseJson.retmsg == null ? "密码修改失败" : responseJson.retmsg)
                    })
                }
            })
            .catch((error) => {
                //Toast.show(error == null ? "系统异常" : JSON.stringify(error), {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
                Toast.show("请检查网络设置", {duration: Toast.durations.SHORT, position: Toast.positions.BOTTOM});
                this.setState({
                    passwordAlertHeight: 20,
                    passwordAlert: this._MP_renderErrorMsg('请检查网络设置')
                })
            });
        }
    }


    //显示重置手势密码modal
    resetCockpitGesturePassword(){
        this.refs.resetCockpitGesturePasswordModal.showModal();
    }
    
    //跳转手势密码页面
    toCockpitGesturePasswordPage(){
        const { p_navigator } = this.props;
        if(p_navigator) {
            p_navigator.push({
                component: CockpitResetGesturePassword,
            })
        }
    }
    //确定重置手势密码
    confirm_resetGP(){
        this.refs.resetCockpitGesturePasswordModal.hiddenModal();
        storage.load({
            key: 'GesturePassword' + global.userid,
        }).then(ret => {
            storage.remove({key: 'GesturePassword' + global.userid});
            
            this.toCockpitGesturePasswordPage();
        }).catch(err => {
            this.toCockpitGesturePasswordPage();
        });
    }

    //退出账号
    exit() {
        // ExitAndroid.exit();
        storage.remove({key: 'user'}).then(ret=>{
            const { p_navigator } = this.props;
            if(p_navigator) {
                p_navigator.popToTop();
            }
        }).catch(err=>{
            const { p_navigator } = this.props;
            if(p_navigator) {
                p_navigator.popToTop();
            }
        });
    }



    _storageClear(){
        for(var i = 0;i < items.length;i++){
            storage.remove({
                key:String(items[i].card)
            });
        }
        this.refs.storageClearModal.hiddenModal();
    }


    _storageClearModal(){
        this.refs.storageClearModal.showModal();
    }

  
    render() {
        return (
            <View style={styles.container} >
                <View style={{height: 60}}>
                    <Head _onLeftPress={()=>alert('left')} _onRightPress={()=> alert('right')} title='设置'></Head>
                </View>
                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this.versionCheck.bind(this)}>
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/download.png')}
                            />
                            <Text style={styles.lineText}>版本更新</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this.passwordModalShow.bind(this)}>
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/unlocked.png')}
                            />
                            <Text style={styles.lineText}>密码修改</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this.resetCockpitGesturePassword.bind(this)}>
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/squared9.png')}
                            />
                            <Text style={styles.lineText}>重置手势密码</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this.aboutModalShow.bind(this)}>
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/information.png')}
                            />
                            <Text style={styles.lineText}>关于</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this.exitModalShow.bind(this)} >
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/undo.png')}
                            />
                            <Text style={styles.lineText}>退出账号</Text>
                        </View>
                    </TouchableOpacity>
                </View>


                <View style={styles.contentContainer}>
                    <TouchableOpacity style={styles.line} onPress={this._storageClearModal.bind(this)}>
                        <View style={styles.lineLeft}>
                            <Image
                                style={styles.icon}
                                source={require('../images/storageClear.png')}
                            />
                            <Text style={styles.lineText}>初始化</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                
                <CockpitModal ref="iosVersionModal" titleText="请联系管理员更新版本" confirm={()=>{this.refs.iosVersionModal.hiddenModal()}} animationType="fade">
                    
                </CockpitModal>

                <CockpitModal ref="versionModal" titleText="是否更新" confirm={(modalVal)=>{this.versionDownload()}} animationType="fade">
                    <View style={{justifyContent: 'center'}}>
                        <Image
                            style={[styles.icon, {width: 80, height: 80, margin: 5, alignSelf: 'center'}]}
                            source={require('../images/logo.png')}
                        />
                        <Text style={[styles.lineText, {fontSize: 14, color: '#000000cc', alignSelf: 'center', marginBottom: 20}]}>当前版本 {this.state.nowVersion}</Text>
                        <Text style={[styles.lineText, {fontSize: 22, color: '#000000bb', alignSelf: 'center', marginBottom: 5}]}>最新版本 {this.state.lastestVersion}</Text>
                    </View>
                </CockpitModal>
                
                <CockpitModal ref="passwordModal" titleText="密码修改" confirm={(modalVal)=>{this._ModifyPassword()}}  cancel={(modalVal)=>{this._ModifySet()}} animationType="fade">
                    <View style={{marginVertical: 5}}>
                        <View style={{height: this.state.passwordAlertHeight}}>
                            {this.state.passwordAlert}
                        </View>
                        <TextInput
                            style={styles.TextInput}
                            placeholder="请输入密码"
                            autoCorrect={false}
                            secureTextEntry={true}
                            underlineColorAndroid='transparent'
                            onChangeText={(text) => this.updateLoginName_Old(text)}
                        />
                        <TextInput
                            style={styles.TextInput}
                            placeholder="请输入新密码"
                            autoCorrect={false}
                            secureTextEntry={true}
                            underlineColorAndroid='transparent'
                            onChangeText={(text) => this.updateLoginName_New(text)}
                        />
                        <TextInput
                            style={styles.TextInput}
                            placeholder="请重新输入新密码"
                            autoCorrect={false}
                            secureTextEntry={true}
                            underlineColorAndroid='transparent'
                            onChangeText={(text) => this.updateLoginName_again(text)}
                        />
                    </View>
                </CockpitModal>

                <CockpitModal ref="resetCockpitGesturePasswordModal" titleText="重置手势密码?" confirm={this.confirm_resetGP.bind(this)} animationType="fade">
                    
                </CockpitModal>

                <CockpitModal ref="aboutModal" titleText="关于" confirm={()=>{this.refs.aboutModal.hiddenModal()}} animationType="fade">
                    <View style={{justifyContent: 'center'}}>
                        <Image
                            style={[styles.icon, {width: 80, height: 80, margin: 5, alignSelf: 'center'}]}
                            source={require('../images/logo.png')}
                        />
                        <Text style={[styles.lineText, {fontSize: 14, color: '#000000cc', alignSelf: 'center', marginBottom: 20}]}>贷前调查 version 1.0.0</Text>
                        <Text style={[styles.lineText, {fontSize: 22, color: '#000000bb', alignSelf: 'center', marginBottom: 5}]}>联系人</Text>
                        <Text style={[styles.lineText, {fontSize: 20, color: '#000000bb', alignSelf: 'center', marginBottom: 5}]}>陈小年: 18061455271</Text>
                    </View>
                </CockpitModal>
                
                <CockpitModal ref="storageClearModal" titleText="确定初始化数据？" confirm={this._storageClear.bind(this)} animationType="fade">
                </CockpitModal>
                <CockpitModal ref="exitModal" titleText="确定退出？" confirm={this.exit.bind(this)} animationType="fade">
                </CockpitModal>
                
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ffffff'
    },
    contentContainer: {
        height: 50,
        paddingLeft: 10,
        paddingRight: 10,
        borderBottomWidth: 1,
        borderColor: '#cdcdcd',
    },
    line: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 50
    },
    lineLeft: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    lineText: {
        alignItems: 'center',
        fontSize: 24,
        marginLeft: 10,
        color: "#00000065",
    },
    icon: {
        width: 40,
        height: 40
    },





  TextInput: {
    backgroundColor: '#00000000',
    borderColor:'#12b7f5',
    borderWidth:1,
    //设置圆角程度
    borderRadius: 5,
    // width: windowWidth - 50,
    height: 40,
    paddingLeft: 10,
    paddingRight: 10,
    //根据不同平台进行适配
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 20,
    marginRight: 20,
  },









  modalStyle: {  
    backgroundColor:'#00000099',
    
    alignItems: 'center',  
    justifyContent:'center',  
    flex:1,  
  },  
  // modal上子View的样式  
  subView:{
    marginLeft:30,  
    marginRight:30,  
    backgroundColor:'#ffffff',  
    alignSelf: 'stretch',  
    justifyContent:'center',  
    borderRadius: 10,  
    borderWidth: 0.5,  
    borderColor:'#ccc',
  },  
  // 标题  
  titleText:{  
    marginTop:5,  
    marginBottom:5,  
    fontSize:16,  
    fontWeight:'bold',  
    textAlign:'center',  
  },  
  // 内容  
  contentText:{  
    margin:8,  
    fontSize:14,  
    textAlign:'left',  
  },  
  // 水平的分割线  
  horizontalLine:{  
    marginTop:5,  
    height:0.5,  
    backgroundColor:'#ccc',  
  },  
  // 按钮  
  buttonView:{  
    flexDirection: 'row',  
    alignItems: 'center',  
  },  
  buttonStyle:{  
    flex:1,  
    height:40,  
    alignItems: 'center',  
    justifyContent:'center',  
  },  
  // 竖直的分割线  
  verticalLine:{  
    width:0.5,  
    height:40,  
    backgroundColor:'#ccc',  
  },  
  buttonText:{  
    fontSize:16,  
    color:'#3393F2',  
    textAlign:'center',  
  }, 


    //密码修改错误提示
    passAlert:{
        flex:1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        height:20,
    },
});

